"""
对webdriver方法的二次封装
"""
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import ElementClickInterceptedException



I_EXCEPTIONS = (StaleElementReferenceException, ElementNotInteractableException, ElementClickInterceptedException)

class BasePage(object):

    def __init__(self, driver, timeout=10):
        self.driver = driver
        self.timeout = timeout

    def get(self, url):
        self.driver.get(url)

    def maximize_window(self):
        self.driver.maximize_window()


    def find_element(self, *locator):
        web_element = WebDriverWait(self.driver, self.timeout).until(
            ec.presence_of_element_located(locator)
        )
        return Element(self.driver, web_element, locator, self.timeout)

    def find_elements(self, *locator):
        web_elements =  WebDriverWait(self.driver, self.timeout).until(
            ec.presence_of_all_elements_located(locator)
        )
        return [Element(self.driver, item, locator, self.timeout) for item in web_elements]

class Element(object):
    def __init__(self, driver,  web_element, locator, time_out=10):
        self.__driver = driver
        self.__element = web_element
        self.__timeout = time_out
        self.__locator = locator


    def send_keys(self, content):
        self.__element.send_keys(content)

    def click(self):
        # self.__waiter.until(
        #     lambda d: not self.__element.click()
        # )
        WebDriverWait(
            self.__driver,
            self.__timeout,
            ignored_exceptions=I_EXCEPTIONS
        ).until(
            lambda d: not d.find_element(*self.__locator).click()
        )

